/**
 * Created by udi on 17-4-11.
 */

import swagger_markdown from "@/api/swagger_markdown.js";
import api_markdown from "@/api/api_markdown.js";
import api_encode_markdown from "@/api/api_encode_markdown.js";
import table_markdown from "@/api/table_markdown.js";
import "./enums.js"


jv.chk_main = v => {
	return jv.main.vnode.el.chk(v)
}

/**
 * 当前系统设置选项
 * @type {*|{}}
 */
jv.currentSetting = jv.currentSetting || {};
jv.me = jv.me || {user: {}, corp: {}}

/**
 * 加载系统设置选项
 * @returns {Promise<Awaited<{id}|*>>|*}
 */
jv.loadSetting = () => {
	if (top.jv.currentSetting && top.jv.currentSetting.id) {
		return Promise.resolve(top.jv.currentSetting);
	}

	return jv.$http.get("/dev/app-deploy-setting/detail").then(res => {
		var currentSetting = res.data.data;
		currentSetting.pipelineTemplate_res = "";
		currentSetting.clusterDeployEnv_res = "";
		if (currentSetting.pipelineTemplate) {
			currentSetting.pipelineTemplate_res = jv.enum.PipelineTemplateEnum.getData(currentSetting.pipelineTemplate).remark;
		}
		if (currentSetting.clusterDeployEnv) {
			currentSetting.clusterDeployEnv_res = jv.enum.MicroServiceDeployEnvEnum.getData(currentSetting.clusterDeployEnv).remark;
		}


		top.jv.currentSetting = currentSetting;
		return currentSetting;
	});
}


jv.getTabUrlByName = name => {
	return JSON.parse(localStorage.getItem("tabs") || "{}")[name];
}

/**
 * 打开指定的tab选项卡页面
 * @param menu
 */
jv.openTabPage = menu => {
	if (!menu) {
		return;
	}

	var menusMeta = JSON.parse(localStorage.getItem("menuMeta") || "{}");


	var name = "";
	var url = "";
	var type = menu.getJsType();
	if (type == "string") {
		url = menu;
		name = menusMeta[url] || jv.getRouteMetaTabName(url);
	} else {
		url = menu.url;
		name = menu.name;

		//如果不同，则指定 menu 的！
		var meta = jv.getRouteMetaTabName(url);
		if (meta != name) {
			menusMeta[url] = name;
			localStorage.setItem("menuMeta", JSON.stringify(menusMeta))
		}
	}

	if (!url) {
		return;
	}


	if (jv.isFullUrl(url)) {
		window.open(url, "tab-url");
		return;
	}

	var tabs = JSON.parse(localStorage.getItem("tabs") || "{}");
	// var isNew = !(name in tabs);
	tabs[name] = url;
	localStorage.setItem("tabs", JSON.stringify(tabs));
	localStorage.setItem("tabName", name);

	//如果已打开,则重新切换.
	if (jv.getFullPath() != url) {
		jv.$router.push(url);
	}

	// if (isNew) {
	//     jv.refreshTab();
	// }
}

jv.saveTabs = menu => {
	var name = menu.name || localStorage.getItem("tabName");
	if (!name) {
		return;
	}

	var tabs = JSON.parse(localStorage.getItem("tabs") || "{}");
	tabs[name] = menu.url;
	localStorage.setItem("tabs", JSON.stringify(tabs));
}


jv.admin = {};

/**
 * 获取 admin-menu 列表数据
 * @param data
 * @returns {*}
 */
jv.admin.getAdminMenus = (data) => {
	var url = '/admin/admin-menu/list'
	return jv.$http.post(url, data).then(res => {
		return res.data.data;
	});
}


jv.ops = {};

jv.ops.versions = {
	"Java": ["1.8", "11", "17"],
	"Vue": ["node14", "node16", "node18", "node20", "node22"],
	"Node": ["14", "16", "18", "20", "22"],
	"Python": ["3.12", "3.9", "2.7"],
	"Nuxt": ["node14", "node16", "node18", "node20", "node22"],

	//和服务器保持一致
	serverLanguage: ["Java", "Node", "Nuxt"],
	needNginxLanguage: ["Vue"],
	nginxVpathStyle: ["Vue", "Nuxt"]
};


jv.dev = jv.dev || {};
jv.dev.getEditorIndexes = function (lines, editor) {
	if (!editor.txt1 && !editor.txt2 && !editor.txt3 && !editor.txtStart && !editor.txtEnd) {
		return [];
	}

	return lines.findIndexes(it => {
			if (editor.txtStart && !it.startsWith(editor.txtStart)) {
				return false;
			}
			if (editor.txtEnd && !it.endsWith(editor.txtEnd)) {
				return false;
			}

			var prevIndex = -1;
			if (editor.txt1) {
				var index = it.indexOf(editor.txt1, prevIndex);
				if (index < 0) {
					return false;
				}
				prevIndex = index + editor.txt1.length;
			}
			if (editor.txt2) {
				var index = it.indexOf(editor.txt2, prevIndex);
				if (index < 0) {
					return false;
				}
				prevIndex = index + editor.txt2.length;
			}

			if (editor.txt3) {
				var index = it.indexOf(editor.txt3, prevIndex);
				if (index < 0) {
					return false;
				}
			}

			return true;
		}
	);
}

/**
 * 错误时返回 {msg, data}，正确时返回字符串
 * @param line
 * @param editor
 * @returns {string|*}
 */
jv.dev.getEditorResult = function (line, editor) {
	if (!editor.location) {
		return {msg: "匹配行位置不能为空！"}
	}

	if (editor.location == "ReplaceWord") {
		if (!editor.replace) {
			return {msg: "匹配行替换字符串时，要替换的字符串不能为空！"}
		}

		if (!line.includes(editor.replace)) {
			return {msg: "匹配行替换字符串时，找不到要替换的字符串！"}
		}

		return line.replaceAll(editor.replace, editor.content);
	}
	if (editor.location == "ReplaceLine") {
		return editor.content;
	}
	if (editor.location == "Before") {
		return editor.content + "\n" + line;
	}
	if (editor.location == "After") {
		return line + "\n" + editor.content;
	}
	return {msg: "不识别的位置:" + editor.location};
}


var javaMap = {
	string: {String: "\"\""},
	number: {Integer: "0"},
	boolean: {Boolean: "false"},
	map: {Map: "new LinkedHashMap<String,Object>()"},
	"null": {Object: "null"}
};
var kotlinMap = {
	string: {String: "\"\""},
	number: {Int: "0"},
	boolean: {Boolean: "false"},
	map: {"Map<String,Any?>": "mapOf<String,Any?>()"},
	"null": {Any: "null"}
};

var embed = [];
jv.dev.json2Pojo = function (name, obj, lang, param, staticClass, defValue, nullable, deep) {
	if (!deep) {
		embed = [];
	}
	var classPadLeft = " ".repeat(deep * 4);
	var memberPadLeft = " ".repeat((deep + 1) * 4);

	var getFirstKey = function (obj) {
		if (!obj) return null;
		return Object.keys(obj)[0];
	}

	var getFirstValue = function (obj) {
		var key = getFirstKey(obj);
		if (!key) return null;
		return obj[key];
	}

	var getLangType = function (key, type, lang, param) {

		if (lang == "java") {
			var fieldType = getFirstKey(javaMap[type]) || (key.getBigCamelCase() + "Model");
			var fieldValue = "";
			if (defValue) {
				fieldValue = " = " + (getFirstValue(javaMap[type]) || " new " + key.getBigCamelCase() + "Model()")
			}

			if (param == "map") {
				return `
${memberPadLeft}public ${fieldType} get${key.getBigCamelCase()} { return (${fieldType})this.get("${key.getSmallCamelCase()}");}
${memberPadLeft}public set${key.getBigCamelCase()}(${fieldType} v) { this.set("${key.getSmallCamelCase()}", v);}`
			}

			return memberPadLeft + (param == '@data' ? "" : "public ") + fieldType + " " + key + fieldValue + ";"
		}

		if (lang == "kotlin") {
			var fieldType = getFirstKey(kotlinMap[type]) || (key.getBigCamelCase() + "Model");

			if (nullable) {
				fieldType += "?";
			}

			var fieldValue = "";
			if (defValue) {
				fieldValue = " = " + (getFirstValue(kotlinMap[type]) || key.getBigCamelCase() + "Model()")
			}
			return memberPadLeft + "var " + key + ":" + fieldType + fieldValue;
		}
	}
	var getLangListType = function (key, type, lang, param) {

		if (lang == "java") {
			var componentType = getFirstKey(javaMap[type]) || (key.getBigCamelCase() + "Model")
			var fieldType = "List<" + componentType + ">";
			var fieldValue = "";
			if (defValue) {
				fieldValue = " = new ArrayList<" + componentType + ">()"
			}
			return memberPadLeft + (param == '@data' ? "" : "public ") + fieldType + " " + key + fieldValue + ";"
		}

		if (lang == "kotlin") {
			var componentType = getFirstKey(kotlinMap[type]) || (key.getBigCamelCase() + "Model")
			var fieldType = "List<" + componentType + ">";

			if (nullable) {
				fieldType += "?";
			}

			var fieldValue = "";
			if (defValue) {
				fieldValue = " = listOf<" + componentType + ">()"
			}
			return memberPadLeft + "var " + key + ": " + fieldType + " " + fieldValue;
		}
	}
	var valueIsMap = function (value) {
		var keys = Object.keys(value);
		if (!keys.length) {
			return true;
		}
		return keys.filter(it => it.toCharArray().filter(c => c != "_" && !c.getDigitCount().length && !c.getLetterCount().length)).length;
	}

	var members = [];

	Object.keys(obj).forEach(key => {
		var value = obj[key];
		if (jv.isNull(value)) {
			members.push(getLangType(key, "null", lang, param));
			return
		}

		var vType = value.getJsType();

		if (vType == "object") {
			if (valueIsMap(value)) {
				members.push(getLangType(key, "map", lang, param));
				return
			}

			embed.push(jv.dev.json2Pojo(key.getBigCamelCase() + "Model", value, lang, param, staticClass, defValue, nullable, deep + 1));
		} else if (vType == "array") {
			var sValue = value[0];
			if (jv.isNull(sValue)) {
				members.push(getLangListType(key, "string", lang, param));
				return;
			} else {
				var sType = sValue.getJsType();
				if (sType == "object") {
					if (valueIsMap(sValue)) {
						members.push(getLangType(key, "map", lang, param));
						return
					}
					embed.push(jv.dev.json2Pojo(key.getBigCamelCase() + "Model", sValue, lang, param, staticClass, defValue, nullable, deep + 1));
					members.push(getLangListType(key, vType, lang, param));
					return;
				} else if (sType == "array") {
					members.push(getLangListType(key, "string /*!*/", lang, param));
					return;
				} else {
					members.push(getLangListType(key, sType, lang, param));
					return;
				}
			}
		}

		members.push(getLangType(key, vType, lang, param));
	});

	var superClass = "";

	var ret = [];
	var clsDef = "";
	if (lang == "java") {
		if (param == "@data") {
			clsDef += "@Data\n" + classPadLeft
		}
		clsDef += "public"

		if (staticClass) {
			clsDef += " static "
		}

		if (param == "map") {
			superClass += " extend HashMap<String,Object>"
		}
	}


	ret.push(classPadLeft + clsDef + " class " + name + superClass + " { ");
	if (!deep) {
		ret.addAll(embed);
	}

	ret.addAll(members);

	ret.push(classPadLeft + " }")
	return ret.join("\n");

}


jv.dev.swagger_markdown = swagger_markdown;
jv.dev.api_markdown = api_markdown;
jv.dev.api_encode_markdown = api_encode_markdown;
jv.dev.table_markdown = table_markdown;
jv.dev.th_common_headers = "x-app-name,x-app-package-name,x-app-type,x-app-version,x-trigger-at,x-device-id,x-trace-no,x-android-id,x-ga-id,x-ios-idfa,x-ios-idfv,x-adjust-id,x-vpn,x-root,x-emulator".split(",")

jv.size_unit = value => {
	var v = value;
	if (v < 1024) {
		return {value: v.ToRound(), unit: "b"};
	}
	v = v / 1024;
	if (v < 1024) {
		return {value: v.ToRound(), unit: "kb"};
	}
	v = v / 1024;
	if (v < 1024) {
		return {value: v.ToRound(), unit: "mb"};
	}

	v = v / 1024;
	return {value: v.ToRound(), unit: "gb"};
}


/**
 * 直接保存客户端文件
 * @param content
 * @param fileName
 * @param mimeType
 */
jv.saveFile = function (content, fileName, mimeType) {
	mimeType = mimeType || 'text/plain'
	// 创建 Blob 对象
	const blob = new Blob([content], {type: mimeType});

	// 生成临时 URL
	const url = URL.createObjectURL(blob);

	// 创建隐藏的 <a> 标签
	const a = document.createElement('a');
	a.href = url;
	a.download = fileName; // 设置下载文件名
	a.style.display = 'none';

	// 触发点击下载
	document.body.appendChild(a);
	a.click();

	// 清理资源
	setTimeout(() => {
		document.body.removeChild(a);
		URL.revokeObjectURL(url); // 释放内存
	}, 100);
}


jv.saveFileWithPicker = async function (content, fileName) {
	var handle;
	try {
		// 请求文件保存权限
		handle = await window.showSaveFilePicker({
			suggestedName: fileName || 'file.txt'
		});
	} catch (err) {
		if (err.name === 'AbortError') {
			return;
		}

	}

	// 创建可写流
	const writable = await handle.createWritable();

	// 写入内容
	await writable.write(content);

	// 关闭流
	await writable.close();

}


import Push from 'push.js';

if (Push.Permission.has()) {
	Push.Permission.request();
}

jv.notify = (msg) => {
	Push.create(
		document.title,
		{
			body: msg,
			timeout: 5000
		}
	)
}

